/**
 * Created by user on 2018/3/12.
 */
import browser from './browser'
class ReplayVideoPlayer {
  lastTask = null
  play(url, _seekTime, success, ended) {
    let seekTime = _seekTime || 0
    var loadedMeta = false
    if (this.lastTask) {
      this.destroyLastTask()
    }
    this.lastTask = {
      success: success,
      ended: ended,
      loadMetaData: () => {
        if (!loadedMeta || seekTime <= 0 || !browser.trident) {
          return
        }
        loadedMeta = true
        seekTime = 0
        video.currentTime = seekTime
      }
    }
    var video = document.getElementById('replayVideo')
    video.src = url
    video.autoplay = false
    video.addEventListener('play', this.lastTask.success, false)
    video.addEventListener('loadedmetadata', this.lastTask.loadMetaData, false)
    video.addEventListener('ended', this.lastTask.ended, false)
    if (!browser.trident) {
      video.currentTime = seekTime
    }
    video.play()

  }
  destroyLastTask() {
    var video = document.getElementById('replayVideo')
    video.pause()
    video.removeEventListener('play', this.lastTask.success, false)
    video.removeEventListener('ended', this.lastTask.ended, false)
    video.removeEventListener('loadedmetadata', this.lastTask.loadMetaData, false)
    this.lastTask = null
  }
  stop() {
    if (this.lastTask) {
      this.destroyLastTask()
    }
  }
  skipVideo() {
    try {
      this.lastTask && this.lastTask.ended && this.lastTask.ended()
      this.destroyLastTask()
    } catch (e) {}
  }
}
module.exports = new ReplayVideoPlayer()
